package sql

import com.alibaba.druid.pool.DruidDataSource
import java.sql.Connection
import java.sql.SQLException
import java.sql.ResultSet
import java.sql.PreparedStatement
import javax.sql.DataSource

object DBSUtl {
    private var dataSource: DruidDataSource = DruidDataSource()
    var db_address = "127.0.0.1"
    var db_port = "3306"
    var database = "gbgate"
    var db_username = "root"
    var db_password = "123"

    //静态代码块
    init {
        initDataSource()
    }

    fun initDataSource(){
        //获取url
        dataSource.url = "jdbc:mysql://$db_address:$db_port/$database?useUnicode=true&characterEncoding=utf-8"
        //获取用户名
        dataSource.username = db_username
        //获取密码
        dataSource.password = db_password
    }

    //返回dds
    val dBDS: DataSource
        get() =//返回dds
            dataSource
    val conn: Connection?
        get() {
            try {
                return dataSource.connection
            } catch (e: SQLException) {
                e.printStackTrace()
            }
            return null
        }

    /**
     * 获取连接池对象
     * @return
     */
    fun getDataSource(): DataSource {
        return dataSource
    }

    /**
     * 获取连接对象
     * @return
     */
    val connection: Connection?
        get() {
            var connection: Connection? = null
            try {
                connection = dataSource.connection
            } catch (e: SQLException) {
                e.printStackTrace()
            }
            return connection
        }

    /**
     * 关闭结果集
     * @param res
     */
    fun closeRes(res: ResultSet) {
        try {
            res.close()
        } catch (e: SQLException) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭预处理对象
     * @param stmt
     */
    fun closeStmt(stmt: PreparedStatement) {
        try {
            stmt.close()
        } catch (e: SQLException) {
            e.printStackTrace()
        }
    }

    /**
     * 关闭连接资源
     * @param connection
     */
    fun closeCon(connection: Connection) {
        try {
            connection.close()
        } catch (e: SQLException) {
            e.printStackTrace()
        }
    }
}